<template>
  <div class="" v-if="passage != null">
    <span class="title">{{ passage.title }}</span>
    <div class="time-wrap">
      发布时间:
      <span class="time">{{ passage.publishTime }}</span>
    </div>
    <div v-html="passage.content" class="content"></div>

    <div v-for="file in fileList" :key="file.id">
      <img
        :src="'/fileServer' + file.filePath"
        class="show-image"
        :alt="file.fileName"
        v-if="isImage(file.fileName)"
      />
      <a :href="'/fileServer' + file.filePath" v-else>{{ file.fileName }}</a>
    </div>

    <Share />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { useRoute } from "vue-router";
import axios from "axios";
import { ElMessage } from "element-plus";
import Share from "@/components/common/Share.vue";

const OK = 200;
const route = useRoute();
const passage = ref({});
const fileList = ref([]);

const get = async (id) => {
  try {
    const res = await axios.get("/api/passages/" + id);
    console.log(res.data);
    if (res.data.code === OK) {
      passage.value = res.data.data;
      fileList.value = passage.value.fileList;
    } else {
      ElMessage.error("获取文章失败");
    }
  } catch (error) {
    console.error("获取文章失败:", error);
  }
};

const isImage = (fileName) => {
  const ext = fileName.substring(fileName.lastIndexOf(".") + 1);
  return ext === "png" || ext === "jpg";
};

onMounted(() => {
  const id = route.params.id;
  get(id);
});

watch(
  () => route.params.id,
  (newId) => {
    get(newId);
  }
);
</script>

<style scoped>
.title {
  display: block;
  font-size: 24px;
  color: #9a0e14;
  margin-top: 10px;
}
.time-wrap {
  float: right;
  margin-right: 100px;
}
.time {
  display: inline-block;
  margin-top: 20px;
  margin-left: 15px;
  font-size: 18px;
}
.content {
  line-height: 150%;
  padding: 20px;
  text-indent: 35px;
  text-align: left;
}
.show-image {
  width: 420px;
  height: 360px;
}
</style>
